package cn.tedu.charging.order.config;

import cn.tedu.charging.order.consumer.MqttConsumer;
import cn.tedu.charging.order.context.MqttContext;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

@Configuration
@Slf4j
public class MqttClientConfiguration {
    @Value("${charging.emqx.address}")
    private String address;
    @Value("${charging.emqx.username}")
    private String username;
    @Value("${charging.emqx.password}")
    private String password;
    @Autowired
    private MqttContext mqttContext;
    @Bean
    public MqttClient mqttClient() {
        MqttClient mqttClient = null;
        try {
            mqttClient = new MqttClient(
                    address,
                    "charging-client"+ UUID.randomUUID().toString(),
                    new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
//          options.setCleanSession(true);
//          options.setConnectionTimeout(10);
//          options.setKeepAliveInterval(60);
//          options.setAutomaticReconnect(true);
            mqttClient.setCallback(new MqttConsumer(mqttClient,mqttContext));
            mqttClient.connect(options);
        } catch (Exception e) {
            log.debug("客户端创建失败，无法实现有效对象使用");
        }
        return mqttClient;
    }
}
